package com.haizhi.crm.biz.dao;

import com.haizhi.crm.biz.constant.MessageSourceType;
import com.haizhi.crm.biz.constant.MessageStatus;
import com.haizhi.crm.biz.model.MessageUserDo;
import com.haizhi.crm.biz.model.MessageVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by wangshan on 2018/5/16.
 */
@Transactional
@Repository
public interface MessageUserDao extends JpaRepository<MessageUserDo, Long> {

    @Modifying
    @Query(value = "update ts_message_user tmu set tmu.msg_status=:status where tmu.user_id=:userId", nativeQuery = true)
    int updateUserStatus(@Param("userId" ) Long userId, @Param("status" ) String status);

    @Modifying
    @Query(value = "update ts_message_user tmu set tmu.msg_status=:status where tmu.user_id=:userId and tmu.msg_id=:msgId", nativeQuery = true)
    int updateMsgUserStatus(@Param("userId" ) Long userId, @Param("msgId" ) Long msgId, @Param("status" ) String status);

    @Query(value = "select count(*) from ts_message_user as tmu where tmu.user_id=:userId and tmu.msg_status=:status", nativeQuery = true)
    int findCountByStatus(@Param("userId" ) Long userId, @Param("status" ) String status);

    @Query("select new com.haizhi.crm.biz.model.MessageVo(tm.msgTitle,tm.msgCategoryId,tm.msgKey,tm.createdDt,tm.id,tmc.name,tmu.status) from MessageUserDo tmu inner join MessageDo tm on tmu.msgId=tm.id " +
            "inner join MessageCategoryDo tmc on tmc.id=tm.msgCategoryId " +
            "inner join MessageUserResourceDo tmur on tmur.messageUserId=tmu.id where tmu.userId=:userId and tmu.status in (:status) and tmur.messageSourceType in (:source)" +
            "and tm.msgCategoryId in (:msgCategorys) group by tm.msgTitle,tm.msgCategoryId,tm.msgKey,tm.createdDt,tm.id,tmc.name,tmu.status order by tmu.status desc,tm.createdDt desc " )
    Page<MessageVo> findMessage(@Param("userId" ) Long userId, @Param("status" ) List<MessageStatus> status, @Param("source" ) List<MessageSourceType> source, @Param("msgCategorys" ) List<Long> msgCategorys, Pageable pageable);

    void deleteByUserIdAndAndMsgId(Long userId, Long msgId);

}
